package com.joker.orange.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.joker.common.constant.UserConstants;
import com.joker.common.core.domain.entity.SysDept;
import com.joker.common.core.domain.entity.SysUser;
import com.joker.common.core.page.TableDataInfo;
import com.joker.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.joker.common.helper.DataBaseHelper;
import com.joker.common.utils.StreamUtils;
import com.joker.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.joker.orange.domain.bo.NovelInfoBo;
import com.joker.orange.domain.vo.NovelInfoVo;
import com.joker.orange.domain.NovelInfo;
import com.joker.orange.mapper.NovelInfoMapper;
import com.joker.orange.service.INovelInfoService;

import java.util.*;

/**
 * 小说信息Service业务层处理
 *
 * @author Joker
 * @date 2024-06-09
 */
@RequiredArgsConstructor
@Service
public class NovelInfoServiceImpl implements INovelInfoService {

    private final NovelInfoMapper baseMapper;

    /**
     * 查询小说信息
     */
    @Override
    public NovelInfoVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public NovelInfo getNovelInfo(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 查询小说信息列表
     */
    @Override
    public TableDataInfo<NovelInfoVo> queryPageList(NovelInfoBo bo, PageQuery pageQuery) {
        Page<NovelInfoVo> result = baseMapper.queryPageList(pageQuery.build(), this.buildPageQueryWrapper(bo));
        return TableDataInfo.build(result);
    }

    private Wrapper<NovelInfo> buildPageQueryWrapper(NovelInfoBo bo) {
        QueryWrapper<NovelInfo> wrapper = Wrappers.query();
        wrapper.eq(ObjectUtil.isNotNull(bo.getCategoryId()), "n.category_id", bo.getCategoryId())
            .like(StringUtils.isNotBlank(bo.getNovelName()), "n.novel_name", bo.getNovelName())
            .eq(StringUtils.isNotBlank(bo.getNovelLabel()), "n.novel_label", bo.getNovelLabel())
            .like(StringUtils.isNotBlank(bo.getNovelType()), "n.novel_type", bo.getNovelType());
        return wrapper;
    }

    /**
     * 查询小说信息列表
     */
    @Override
    public List<NovelInfoVo> queryList(NovelInfoBo bo) {
        LambdaQueryWrapper<NovelInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<NovelInfo> listAllNovel() {
        return baseMapper.selectList();
    }

    private LambdaQueryWrapper<NovelInfo> buildQueryWrapper(NovelInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<NovelInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCategoryId() != null, NovelInfo::getCategoryId, bo.getCategoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getNovelCoverCopy()), NovelInfo::getNovelCover, bo.getNovelCoverCopy());
        lqw.like(StringUtils.isNotBlank(bo.getNovelName()), NovelInfo::getNovelName, bo.getNovelName());
        lqw.eq(StringUtils.isNotBlank(bo.getCurrentChapter()), NovelInfo::getCurrentChapter, bo.getCurrentChapter());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdateChapter()), NovelInfo::getUpdateChapter, bo.getUpdateChapter());
        lqw.eq(StringUtils.isNotBlank(bo.getChapterTotal()), NovelInfo::getChapterTotal, bo.getChapterTotal());
        lqw.eq(StringUtils.isNotBlank(bo.getNovelIntroduce()), NovelInfo::getNovelIntroduce, bo.getNovelIntroduce());
        lqw.eq(StringUtils.isNotBlank(bo.getNovelLabel()), NovelInfo::getNovelLabel, bo.getNovelLabel());
        lqw.eq(StringUtils.isNotBlank(bo.getNovelType()), NovelInfo::getNovelType, bo.getNovelType());
        lqw.eq(bo.getLikeNum() != null, NovelInfo::getLikeNum, bo.getLikeNum());
        lqw.eq(bo.getCollectNum() != null, NovelInfo::getCollectNum, bo.getCollectNum());
        lqw.eq(bo.getHeatNum() != null, NovelInfo::getHeatNum, bo.getHeatNum());
        lqw.eq(bo.getReviewNum() != null, NovelInfo::getReviewNum, bo.getReviewNum());
        lqw.eq(StringUtils.isNotBlank(bo.getIsTop()), NovelInfo::getIsTop, bo.getIsTop());
        return lqw;
    }

    /**
     * 新增小说信息
     */
    @Override
    public Boolean insertByBo(NovelInfoBo bo) {
        NovelInfo add = BeanUtil.toBean(bo, NovelInfo.class);
        validEntityBeforeSave(add, bo.getNovelCoverCopy());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Long insertNovelInfo(NovelInfo novelInfo) {
        baseMapper.insert(novelInfo);
        return novelInfo.getId();
    }

    /**
     * 修改小说信息
     */
    @Override
    public Boolean updateByBo(NovelInfoBo bo) {
        NovelInfo update = BeanUtil.toBean(bo, NovelInfo.class);
        validEntityBeforeSave(update, bo.getNovelCoverCopy());
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public void updateNovelChapterAndHeatNum(NovelInfoBo bo) {
        baseMapper.updateNovelChapterAndHeatNum(bo);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(NovelInfo entity, String novelCoverCopy){
        entity.setNovelCover(novelCoverCopy);
    }

    /**
     * 批量删除小说信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<NovelInfoVo> getRandomNovels(List<NovelInfoVo> novelInfoVoList, int count) {
        // 返回空列表，如果输入无效
        if (novelInfoVoList == null || novelInfoVoList.size() < count || count <= 0) {
            return new ArrayList<>();
        }
        if (novelInfoVoList.size() <= count) {
            return novelInfoVoList;
        }

        // 复制列表以避免改变原始列表
        List<NovelInfoVo> shuffledList = new ArrayList<>(novelInfoVoList);

        // 打乱列表顺序
        Collections.shuffle(shuffledList);

        // 截取前count个元素作为随机选取的结果
        return shuffledList.subList(0, Math.min(count, shuffledList.size()));
    }
}
